/**
 * 函数生成器, Generator执行器co
 */

const ajaxQuery = (url) => {
  return new Promise((resolve, reject) => {
    const http = new XMLHttpRequest();
    http.open("GET", url);
    http.responseType = "json";
    http.onload = function () {
      if (this.status === 200) {
        resolve(this.response);
      } else {
        reject(new Error(this.statusText));
      }
    };
    http.send();
  });
};

function* test() {
  try {
    const res = yield ajaxQuery("/08-test/data.json");
    console.log(res);
    const res2 = yield ajaxQuery("/08-test3/data2.json");
    console.log(res2);
  } catch (error) {
    console.log(error);
  }
}

const co=(generator)=>{
  const g= generator();
  const handleResult=(result)=>{
    if(result.done) return;
    result.value.then(data=>{
      handleResult(g.next(data))
    },error=>{
      g.throw(error)
    })
  }
  handleResult(g.next())
}
co(test)
